package common

import (
	"context"
	"fmt"
	businessOpportunityDto "git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/dto/business_opportunity"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/dto/common"
	commonRepos "git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/repository/common"
	"sort"
	"strconv"
)

type CommonService struct {
	commonRepos commonRepos.CommonReposIface
}

func NewCommonService(commonRepos commonRepos.CommonReposIface,
) CommonServiceIface {
	return &CommonService{
		commonRepos: commonRepos,
	}
}

func (s *CommonService) GetLocation(ctx context.Context) (common.GetLocationResp, error) {
	list, err := s.commonRepos.GetLocation(ctx)
	if err != nil {
		return nil, err
	}

	resp := make(common.GetLocationResp, 0)
	m := make(map[int][]interface{})
	mkeys := make([]int, 0)
	if list != nil {
		for _, item := range list {
			pId, ok := item["province_id"]
			if !ok {
				continue
			}
			provinceId, ok := pId.(string)
			if !ok {
				continue
			}
			id, _ := strconv.Atoi(provinceId)
			m[id] = append(m[id], item)

			mkeysExist := false
			for _, key := range mkeys {
				if key == id {
					mkeysExist = true
					break
				}
			}
			if !mkeysExist {
				mkeys = append(mkeys, id)
			}
		}
	}

	sort.Ints(mkeys)
	for _, key := range mkeys {
		item, ok := m[key]
		if !ok {
			continue
		}
		var getLocation common.GetLocation
		for _, childrenItem := range item {
			children, ok := childrenItem.(map[string]interface{})
			if !ok {
				continue
			}
			pId, ok1 := children["province_id"]
			pName, ok2 := children["province_name"]
			cId, ok3 := children["city_id"]
			cName, ok4 := children["city_name"]
			if !ok1 || !ok2 || !ok3 || !ok4 {
				continue
			}
			provinceId, ok1 := pId.(string)
			provinceName, ok2 := pName.(string)
			cityId, ok3 := cId.(string)
			cityName, ok4 := cName.(string)
			if !ok1 || !ok2 || !ok3 || !ok4 {
				continue
			}

			if getLocation.Name == "" {
				getLocation = common.GetLocation{
					Name: provinceName,
					Code: provinceId,
				}
			}
			getLocation.Children = append(getLocation.Children, common.GetLocationChildren{
				Name: cityName,
				Code: cityId,
			})
		}
		resp = append(resp, &getLocation)
	}

	return resp, nil

}

func (s *CommonService) GetJmLocation(ctx context.Context) (*common.GetJmLocationResponse, error) {
	locationInfo := make([]common.JmLocations, 0)
	treeLocation, err := s.GetLocation(ctx)
	if err != nil {
		return nil, err
	}
	locationInfo = append(locationInfo, common.JmLocations{
		IsDefault: false,
		Leaf:      false,
		Parent:    "-1",
		Text:      "全国",
		Value:     "0",
	})
	for _, parent := range treeLocation {
		// 处理父级
		locationInfo = append(locationInfo, common.JmLocations{
			IsDefault: false,
			Leaf:      false,
			Parent:    "0",
			Text:      parent.Name,
			Value:     parent.Code,
		})
		if len(parent.Children) > 0 {
			for _, child := range parent.Children {
				locationInfo = append(locationInfo, common.JmLocations{
					IsDefault: false,
					Leaf:      false,
					Parent:    parent.Code,
					Text:      child.Name,
					Value:     child.Code,
				})
			}
		}
	}

	area := common.JmLocationsResult{
		Area: locationInfo,
	}
	response := common.GetJmLocationResponse{
		Success: true,
		Result:  area,
	}

	return &response, nil
}

func (s *CommonService) FuzzySearchCompanyInfo(ctx context.Context, keyword string) (interface{}, error) {
	list, err := s.commonRepos.FuzzySearchCompanyInfo(ctx, keyword)
	if err != nil {
		return nil, err
	}
	fmt.Printf("list: %#v\n", list)

	return list, nil
}

func (s *CommonService) GetProjectListByCompanyName(ctx context.Context, req *businessOpportunityDto.GetProjectListByCompanyNameRequest) (map[string]interface{}, error) {
	resp := map[string]interface{}{
		"total": 0,
		"list":  make([]map[string]string, 0),
	}
	dataTypeMap := map[string]string{
		"土地交易": "1",
		"在建项目": "2",
		"开盘项目": "3",
	}
	if req.CompanyType == 1 {
		//	开发商
		list, total, err := s.commonRepos.GetProjectListByDeveloperName(ctx, req)
		if err != nil {
			return nil, err
		}
		resp["total"] = total
		if list != nil {
			data := make([]map[string]string, 0)
			for _, item := range list {
				t := map[string]string{
					"project_name":  "",
					"project_type":  "",
					"province":      "",
					"province_code": "",
					"city":          "",
					"city_code":     "",
					"data_type":     "",
				}
				dataType := ""
				v, ok := item["data_type"]
				if ok {
					if value, ok := v.(string); ok {
						dataType = value
					}
				}
				for k, v := range item {
					switch k {
					case "project_title":
						if value, ok := v.(string); ok && dataType != "土地交易" {
							t["project_name"] = value
						}
					case "land_title":
						if value, ok := v.(string); ok && dataType == "土地交易" {
							t["project_name"] = value
						}
					case "province":
						if value, ok := v.(string); ok {
							t["province"] = value
						}
					case "province_code":
						if value, ok := v.(string); ok {
							t["province_code"] = value
						}
					case "city":
						if value, ok := v.(string); ok {
							t["city"] = value
						}
					case "city_code":
						if value, ok := v.(string); ok {
							t["city_code"] = value
						}
					case "land_usage_label_v2":
						if value, ok := v.(string); ok && dataType == "土地交易" {
							t["project_type"] = value
						}
					case "project_label":
						if value, ok := v.(string); ok && dataType == "在建项目" {
							t["project_type"] = value
						}
					}
				}
				dataType, ok = dataTypeMap[item["data_type"].(string)]
				if ok {
					t["data_type"] = dataType
				}
				data = append(data, t)
			}
			resp["list"] = data
		}
	} else {
		//	供应商
		list, total, err := s.commonRepos.GetProjectListBySupplierName(ctx, req)
		if err != nil {
			return nil, err
		}
		resp["total"] = total
		if list != nil {
			data := make([]map[string]string, 0)
			for _, item := range list {
				t := map[string]string{
					"project_name":  "",
					"project_type":  "",
					"province":      "",
					"province_code": "",
					"city":          "",
					"city_code":     "",
					"data_type":     "",
				}
				for k, v := range item {
					switch k {
					case "coop_prj_name":
						if value, ok := v.(string); ok {
							t["project_name"] = value
						}
					case "coop_province":
						if value, ok := v.(string); ok {
							t["province"] = value
						}
					case "coop_province_code":
						if value, ok := v.(string); ok {
							t["province_code"] = value
						}
					case "coop_city":
						if value, ok := v.(string); ok {
							t["city"] = value
						}
					case "coop_city_code":
						if value, ok := v.(string); ok {
							t["city_code"] = value
						}
					}
				}
				data = append(data, t)
			}
			resp["list"] = data
		}
	}

	return resp, nil
}
